'use client';

import { Button, Form, Input, Modal, Popconfirm, Space, TreeSelect, message, Select } from 'antd';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { useRef, useState, useEffect } from 'react';
import ImageUpload from '@/components/ImageUpload';
import RichTextEditor from '@/components/RichTextEditor';
import { getContentList, createContent, updateContent, deleteContent } from '@/apis/admin/content';
import { Content } from '@/types/content';
import { getCategoryList } from '@/apis/admin/category';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { getAgentList } from '@/apis/admin/agent';
import { Agent } from '@/types/agent';
import { syncContentIcon } from '@/apis/admin/content';

const ContentsPage = () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>(null);

  const [isOpen, setIsOpen] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [isClient, setIsClient] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  const { data: categoryTree } = useRequest(getCategoryList);
  const { data: agentList } = useRequest(getAgentList);
  const typeValue = Form.useWatch('type', form);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const handleSyncIcon = async (record: Content) => {
    if (!record.url || !record.url.startsWith('http')) {
      message.error('请先填写合法的站点地址');
      return;
    }
    const hide = message.loading('正在同步图标...', 0);
    try {
      await syncContentIcon(record.id);
      message.success('同步成功');
      actionRef.current?.reload();
    } catch (e) {
      console.error(e);
      message.error('同步失败');
    } finally {
      hide();
    }
  };

  const handleBatchSync = async () => {
    if (selectedRowKeys.length === 0) {
      message.info('请先选择需要同步的内容');
      return;
    }
    const hide = message.loading('批量同步中...', 0);
    try {
      const results = await Promise.allSettled(selectedRowKeys.map((id) => syncContentIcon(id)));
      const successCount = results.filter(r => r.status === 'fulfilled').length;
      const failCount = results.length - successCount;
      message.success(`同步完成：成功 ${successCount} 条，失败 ${failCount} 条`);
      actionRef.current?.reload();
      setSelectedRowKeys([]);
    } catch (e) {
      console.error(e);
      message.error('批量同步失败');
    } finally {
      hide();
    }
  };

  const handleEdit = (record: Content) => {
    setIsOpen(true);
    setEditId(record.id);
    form.setFieldsValue({
      ...record,
      categoryIds: record.categories.map((c) => c.id),
    });
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ...values,
        coverId: values.cover?.id,
      };
      if (editId) {
        await updateContent({ id: editId, ...payload });
        message.success('更新成功');
      } else {
        await createContent(payload);
        message.success('创建成功');
      }
      setIsOpen(false);
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteContent({ id });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      console.error(error);
    }
  };

  const columns: ProColumns<Content>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '分类',
      dataIndex: 'categories',
      render: (_, record) => record.categories?.map((cat) => cat.name).join(', '),
      search: false,
    },
    {
      title: '封面',
      dataIndex: 'cover',
      render: (_, record) => <img src={record.cover?.url || ''} alt="cover" style={{ width: 100 }} />,
      search: false,
    },
    {
      title: '站点地址',
      dataIndex: 'url',
      render: (_, record) => (record.url ? (
        <a href={record.url} target="_blank" rel="noopener noreferrer">{record.url}</a>
      ) : (
        '-'
      )),
      search: false,
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: { text: '网站' },
        2: { text: '智能体' },
        3: { text: '资讯' },
      },
    },
    {
      title: '是否为Banner',
      dataIndex: 'isBanner',
      valueEnum: {
        0: { text: '否' },
        1: { text: '是' },
      },
    },
    {
      title: '查看数',
      dataIndex: 'viewCount',
      key: 'viewCount',
      search: false,
      sorter: true,
    },
    {
      title: "收藏数",
      dataIndex: "favoritesCount",
      key: "favoritesCount",
      search: false,
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_: any, record: Content) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <a onClick={() => handleSyncIcon(record)}>同步图标</a>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {isClient && (
        <>
          <ProTable<Content>
            columns={columns}
            actionRef={actionRef}
            request={async (params) => {
              const { data, total } = await getContentList({ page: params.current, pageSize: params.pageSize, title: params.title, type: params.type, isBanner: params.isBanner });
              return { data, total };
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (keys) => setSelectedRowKeys(keys as string[]),
            }}
            search={{
              labelWidth: 'auto',
            }}
            toolBarRender={() => [
              <Button
                key="add"
                type="primary"
                onClick={() => {
                  setIsOpen(true);
                  setEditId(null);
                  form.resetFields();
                }}
              >
                新增
              </Button>,
              <Button key="batchSync" disabled={selectedRowKeys.length === 0} onClick={handleBatchSync}>
                批量同步图标
              </Button>,
            ]}
          />
          <Modal title={editId ? '编辑' : '新增'} open={isOpen} onOk={handleOk} onCancel={() => setIsOpen(false)}>
            <Form form={form} layout="vertical">
              <Form.Item label="标题" name="title" rules={[{ required: true }]}> 
                <Input />
              </Form.Item>
              <Form.Item label="分类" name="categoryIds" rules={[{ required: true }]}> 
                <TreeSelect treeData={categoryTree} fieldNames={{ label: 'name', value: 'id' }} treeCheckable treeDefaultExpandAll />
              </Form.Item>
              <Form.Item label="封面" name="cover" rules={[{ required: true }]}> 
                <ImageUpload />
              </Form.Item>
              <Form.Item label="简述" name="summary" rules={[{ max: 500, message: '简述不超过500字' }]}>
                <Input.TextArea rows={3} placeholder="一句话概述或简短介绍" />
              </Form.Item>
              <Form.Item
                label="内容"
                name="content"
                rules={[{ required: true, message: '请输入内容' }]}
                valuePropName="value"
                getValueFromEvent={(value) => value}
              >
                <RichTextEditor height={300} />
              </Form.Item>
              <Form.Item label="站点地址" name="url" rules={[{ type: 'url', message: '请输入合法网址' }]}> 
                <Input placeholder="https://example.com" />
              </Form.Item>
              <Form.Item label="类型" name="type" rules={[{ required: true }]}> 
                <Select>
                  <Select.Option value={1}>网站</Select.Option>
                  <Select.Option value={2}>智能体</Select.Option>
                  <Select.Option value={3}>资讯</Select.Option>
                </Select>
              </Form.Item>
              {typeValue === 2 && (
                <Form.Item label="智能体" name="agentId" rules={[{ required: true, message: '请选择智能体' }]}>
                  <Select>
                    {agentList?.map((agent: Agent) => (
                      <Select.Option key={agent.id} value={agent.id}>
                        {agent.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              )}
              <Form.Item label="是否为Banner" name="isBanner" rules={[{ required: true }]}> 
                <Select>
                  <Select.Option value={1}>是</Select.Option>
                  <Select.Option value={0}>否</Select.Option>
                </Select>
              </Form.Item>
            </Form>
          </Modal>
        </>
      )}
    </div>
  );
};

export default ContentsPage;